#!/usr/bin/env python
# encoding: utf-8

"""
@file: trig_condition_converts.py
@time: 2017/2/22 上午11:02
"""
from functools import reduce
from mathsolver.functions.base import *
from sympy import sin, cos, expand_trig, tan, cot
from mathsolver.functions.budengshi import common_opers as co
from mathsolver.functions.sanjiao import Jiao


# 三角函数的条件等价装换

# 最简单的已知cot, tan, sin, cos中的一个值求其他三个值
def _convert1(cond_eq, quad=1):
    cond_l, cond_r = cond_eq.sympify()
    cond_f = expand_trig(cond_l - cond_r)
    mo, de = co.complete_fraction(cond_f)
    cond_f = mo
    cond_symbs = list(cond_f.free_symbols)
    if len(cond_symbs) != 1:
        raise Exception('Type Match Error')
    cond_symb = cond_symbs[0]
    cond_subs = ((sin(cond_symb), 'SIN'), (cos(cond_symb), 'COS'), (tan(cond_symb), 'TAN'), (cot(cond_symb), 'COT'))
    eqs = [['SIN**2 + COS**2', '1'], ['TAN*COS', 'SIN'], ['COT*SIN', 'COS'], [cond_f.subs(cond_subs), '0']]
    values_list = co.solve_poly_eqs(BaseEqs(eqs))
    matched = True
    for values in values_list:
        matched = matched and reduce(lambda b1, b2: b1 and b2, map(lambda pair: pair[1].is_real, values))
    if not matched:
        raise Exception('Type Match Error')
    cond_reverse_subs = map(lambda pair: (pair[1], pair[0]), cond_subs)
    new_values_list = []
    for values in values_list:
        tmp_values = map(lambda pair: [pair[0].subs(cond_reverse_subs), pair[1]], values)
        sin_v = dict(tmp_values)[sin(cond_symb)]
        sin_pm = Jiao.trig_f_quad_pm('sin')[quad - 1]
        if sin_v * sin_pm > 0:
            new_values_list.append(tmp_values)
    return new_values_list[0]


# print _convert1(BaseEq(['tan(pi/4+x)', '-3']))

_converts = [_convert1, ]


def condition_converts(eq, quad):
    convert_eqs = []
    for convert in _converts:
        try:
            eqs = convert(eq, quad)
            convert_eqs.extend(eqs)
        except Exception:
            pass
    return convert_eqs
